document.addEventListener('DOMContentLoaded', function() {
    const characterParts = {
        head: null,
        body: null,
        clothes: null,
        weapon: null
    };

    function drawPixel(ctx, x, y, color, size = 10) {
        ctx.fillStyle = color;
        ctx.fillRect(x * size, y * size, size, size);
    }

    function drawHead(canvas, data) {
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 绘制面部
        for(let y = 5; y < 15; y++) {
            for(let x = 5; x < 15; x++) {
                drawPixel(ctx, x, y, data.face_color);
            }
        }

        // 绘制眼睛
        drawPixel(ctx, 7, 8, '#000000');
        drawPixel(ctx, 12, 8, '#000000');

        // 绘制嘴巴
        if(data.mouth_type === 'smile') {
            drawPixel(ctx, 9, 11, '#000000');
            drawPixel(ctx, 10, 11, '#000000');
        }

        // 绘制头发
        for(let x = 4; x < 16; x++) {
            drawPixel(ctx, x, 4, data.hair_color);
        }
    }

    function drawBody(canvas, data) {
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 简单的身体轮廓
        for(let y = 5; y < 15; y++) {
            for(let x = 7; x < 13; x++) {
                drawPixel(ctx, x, y, data.color);
            }
        }
    }

    function drawClothes(canvas, data) {
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 简单的衣服轮廓
        for(let y = 8; y < 15; y++) {
            for(let x = 6; x < 14; x++) {
                drawPixel(ctx, x, y, data.color);
            }
        }
    }

    function drawWeapon(canvas, data) {
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        const size = data.size === 'large' ? 12 : data.size === 'medium' ? 10 : 8;
        
        switch(data.type) {
            case 'sword':
                // 剑柄
                drawPixel(ctx, 10, 5, '#8B4513', size);
                drawPixel(ctx, 10, 6, '#8B4513', size);
                // 剑身
                for(let y = 7; y < 15; y++) {
                    drawPixel(ctx, 10, y, data.color, size);
                }
                // 剑护手
                drawPixel(ctx, 9, 7, data.color, size);
                drawPixel(ctx, 11, 7, data.color, size);
                break;

            case 'staff':
                // 法杖杆
                for(let y = 5; y < 15; y++) {
                    drawPixel(ctx, 10, y, '#8B4513', size);
                }
                // 法杖头
                drawPixel(ctx, 9, 4, data.color, size);
                drawPixel(ctx, 10, 3, data.color, size);
                drawPixel(ctx, 11, 4, data.color, size);
                break;

            case 'bow':
                // 弓身
                drawPixel(ctx, 8, 5, data.color, size);
                drawPixel(ctx, 9, 6, data.color, size);
                drawPixel(ctx, 10, 7, data.color, size);
                drawPixel(ctx, 11, 6, data.color, size);
                drawPixel(ctx, 12, 5, data.color, size);
                // 弓弦
                drawPixel(ctx, 8, 8, '#FFFFFF', size);
                drawPixel(ctx, 12, 8, '#FFFFFF', size);
                break;

            case 'axe':
                // 斧柄
                for(let y = 7; y < 15; y++) {
                    drawPixel(ctx, 10, y, '#8B4513', size);
                }
                // 斧头
                drawPixel(ctx, 8, 6, data.color, size);
                drawPixel(ctx, 9, 6, data.color, size);
                drawPixel(ctx, 11, 6, data.color, size);
                drawPixel(ctx, 12, 6, data.color, size);
                drawPixel(ctx, 9, 7, data.color, size);
                drawPixel(ctx, 11, 7, data.color, size);
                break;

            case 'spear':
                // 矛杆
                for(let y = 7; y < 15; y++) {
                    drawPixel(ctx, 10, y, '#8B4513', size);
                }
                // 矛头
                drawPixel(ctx, 9, 5, data.color, size);
                drawPixel(ctx, 10, 4, data.color, size);
                drawPixel(ctx, 11, 5, data.color, size);
                drawPixel(ctx, 10, 6, data.color, size);
                break;

            case 'shield':
                // 盾牌主体
                for(let y = 6; y < 14; y++) {
                    for(let x = 8; x < 13; x++) {
                        drawPixel(ctx, x, y, data.color, size);
                    }
                }
                // 盾牌边框
                drawPixel(ctx, 9, 5, '#000000', size);
                drawPixel(ctx, 10, 5, '#000000', size);
                drawPixel(ctx, 11, 5, '#000000', size);
                break;
        }

        // 添加武器特效
        if (data.effect !== 'normal') {
            const effectColors = {
                'flame': '#FF4500',
                'ice': '#87CEEB',
                'lightning': '#FFD700',
                'poison': '#32CD32'
            };
            
            // 在武器周围添加特效像素
            for (let i = 0; i < 4; i++) {
                const x = 8 + Math.floor(Math.random() * 5);
                const y = 5 + Math.floor(Math.random() * 10);
                drawPixel(ctx, x, y, effectColors[data.effect], size/2);
            }
        }
    }

    function updatePreview() {
        const previewCanvas = document.getElementById('preview-canvas');
        const ctx = previewCanvas.getContext('2d');
        ctx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
        
        // 基础设置
        const pixelSize = 10;
        const centerX = previewCanvas.width / 2;
        const startY = 150;
        
        // 首先绘制武器（在人物左侧）
        if(characterParts.weapon) {
            const data = characterParts.weapon;
            const weaponScale = data.size === 'large' ? 1.2 : data.size === 'medium' ? 1 : 0.8;
            // 调整武器位置，使其在人物左侧
            const weaponX = centerX - 100; // 增加与人物的距离
            
            // 武器特效
            if (data.effect !== 'normal') {
                const effectColors = {
                    'flame': '#FF4500',
                    'ice': '#87CEEB',
                    'lightning': '#FFD700',
                    'poison': '#32CD32'
                };
                
                // 在武器周围添加特效像素
                for (let i = 0; i < 6; i++) {
                    const effectX = Math.random() * 5 - 2.5;
                    const effectY = Math.random() * 10 - 5;
                    drawPixel(ctx, 
                        weaponX/pixelSize + effectX, 
                        startY/pixelSize + 7 + effectY, 
                        effectColors[data.effect], 
                        pixelSize * weaponScale * 0.5
                    );
                }
            }
            
            switch(data.type) {
                case 'sword':
                    // 剑柄
                    drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + 5, '#8B4513', pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + 6, '#8B4513', pixelSize * weaponScale);
                    // 剑身
                    for(let y = 7; y < 15; y++) {
                        drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + y, data.color, pixelSize * weaponScale);
                    }
                    // 剑护手
                    drawPixel(ctx, weaponX/pixelSize - 1, startY/pixelSize + 7, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 1, startY/pixelSize + 7, data.color, pixelSize * weaponScale);
                    break;

                case 'staff':
                    // 法杖杆
                    for(let y = 5; y < 15; y++) {
                        drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + y, '#8B4513', pixelSize * weaponScale);
                    }
                    // 法杖头
                    drawPixel(ctx, weaponX/pixelSize - 1, startY/pixelSize + 4, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + 3, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 1, startY/pixelSize + 4, data.color, pixelSize * weaponScale);
                    break;

                case 'bow':
                    // 弓身
                    drawPixel(ctx, weaponX/pixelSize - 2, startY/pixelSize + 5, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize - 1, startY/pixelSize + 6, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + 7, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 1, startY/pixelSize + 6, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 2, startY/pixelSize + 5, data.color, pixelSize * weaponScale);
                    // 弓弦
                    drawPixel(ctx, weaponX/pixelSize - 2, startY/pixelSize + 8, '#FFFFFF', pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 2, startY/pixelSize + 8, '#FFFFFF', pixelSize * weaponScale);
                    break;

                case 'axe':
                    // 斧柄
                    for(let y = 7; y < 15; y++) {
                        drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + y, '#8B4513', pixelSize * weaponScale);
                    }
                    // 斧头
                    drawPixel(ctx, weaponX/pixelSize - 2, startY/pixelSize + 6, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize - 1, startY/pixelSize + 6, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 1, startY/pixelSize + 6, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 2, startY/pixelSize + 6, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize - 1, startY/pixelSize + 7, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 1, startY/pixelSize + 7, data.color, pixelSize * weaponScale);
                    break;

                case 'spear':
                    // 矛杆
                    for(let y = 7; y < 15; y++) {
                        drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + y, '#8B4513', pixelSize * weaponScale);
                    }
                    // 矛头
                    drawPixel(ctx, weaponX/pixelSize - 1, startY/pixelSize + 5, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + 4, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 1, startY/pixelSize + 5, data.color, pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + 6, data.color, pixelSize * weaponScale);
                    break;

                case 'shield':
                    // 盾牌主体
                    for(let y = 6; y < 14; y++) {
                        for(let x = -2; x < 3; x++) {
                            drawPixel(ctx, weaponX/pixelSize + x, startY/pixelSize + y, data.color, pixelSize * weaponScale);
                        }
                    }
                    // 盾牌边框
                    drawPixel(ctx, weaponX/pixelSize - 1, startY/pixelSize + 5, '#000000', pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize, startY/pixelSize + 5, '#000000', pixelSize * weaponScale);
                    drawPixel(ctx, weaponX/pixelSize + 1, startY/pixelSize + 5, '#000000', pixelSize * weaponScale);
                    break;
            }
        }
        
        // 绘制身体（作为基准）
        if(characterParts.body) {
            const bodyWidth = 6;  // 身体宽度（像素数）
            const bodyStartX = centerX - (bodyWidth * pixelSize / 2);  // 计算身体起始X坐标使其居中
            
            // 绘制手臂
            // 左手臂
            for(let y = 0; y < 8; y++) {
                drawPixel(ctx, 
                    bodyStartX/pixelSize - 1, 
                    startY/pixelSize + y + 1, 
                    characterParts.body.color, 
                    pixelSize
                );
            }
            // 右手臂
            for(let y = 0; y < 8; y++) {
                drawPixel(ctx, 
                    bodyStartX/pixelSize + bodyWidth, 
                    startY/pixelSize + y + 1, 
                    characterParts.body.color, 
                    pixelSize
                );
            }
            
            // 绘制身体躯干
            for(let y = 0; y < 10; y++) {
                for(let x = 0; x < bodyWidth; x++) {
                    drawPixel(ctx, 
                        bodyStartX/pixelSize + x, 
                        startY/pixelSize + y, 
                        characterParts.body.color, 
                        pixelSize
                    );
                }
            }
            
            // 绘制腿部
            // 左腿
            for(let y = 10; y < 15; y++) {
                drawPixel(ctx, 
                    bodyStartX/pixelSize + 1, 
                    startY/pixelSize + y, 
                    characterParts.body.color, 
                    pixelSize
                );
                drawPixel(ctx, 
                    bodyStartX/pixelSize + 2, 
                    startY/pixelSize + y, 
                    characterParts.body.color, 
                    pixelSize
                );
            }
            // 右腿
            for(let y = 10; y < 15; y++) {
                drawPixel(ctx, 
                    bodyStartX/pixelSize + bodyWidth - 3, 
                    startY/pixelSize + y, 
                    characterParts.body.color, 
                    pixelSize
                );
                drawPixel(ctx, 
                    bodyStartX/pixelSize + bodyWidth - 2, 
                    startY/pixelSize + y, 
                    characterParts.body.color, 
                    pixelSize
                );
            }
        }
        
        // 绘制衣服
        if(characterParts.clothes) {
            const clothesWidth = 8;  // 衣服宽度（像素数）
            const clothesStartX = centerX - (clothesWidth * pixelSize / 2);  // 计算衣服起始X坐标使其居中
            
            // 绘制衣服主体
            for(let y = 5; y < 10; y++) {
                for(let x = 0; x < clothesWidth; x++) {
                    drawPixel(ctx, 
                        clothesStartX/pixelSize + x, 
                        startY/pixelSize + y,
                        characterParts.clothes.color, 
                        pixelSize
                    );
                }
            }
            
            // 绘制衣服袖子
            // 左袖子
            for(let y = 5; y < 8; y++) {
                drawPixel(ctx, 
                    clothesStartX/pixelSize - 1, 
                    startY/pixelSize + y, 
                    characterParts.clothes.color, 
                    pixelSize
                );
            }
            // 右袖子
            for(let y = 5; y < 8; y++) {
                drawPixel(ctx, 
                    clothesStartX/pixelSize + clothesWidth, 
                    startY/pixelSize + y, 
                    characterParts.clothes.color, 
                    pixelSize
                );
            }
        }
        
        // 绘制头部
        if(characterParts.head) {
            const headWidth = 10;  // 头部宽度（像素数）
            const headStartX = centerX - (headWidth * pixelSize / 2);  // 计算头部起始X坐标使其居中
            
            // 面部
            for(let y = 0; y < 10; y++) {
                for(let x = 0; x < headWidth; x++) {
                    drawPixel(ctx, 
                        headStartX/pixelSize + x, 
                        startY/pixelSize - 10 + y, // 头部位置在身体上方
                        characterParts.head.face_color, 
                        pixelSize
                    );
                }
            }
            
            // 眼睛（相对于头部居中）
            const eyeSpacing = 3;  // 眼睛之间的间距
            drawPixel(ctx, 
                headStartX/pixelSize + headWidth/2 - eyeSpacing/2 - 1, 
                startY/pixelSize - 7, 
                '#000000', 
                pixelSize
            );
            drawPixel(ctx, 
                headStartX/pixelSize + headWidth/2 + eyeSpacing/2, 
                startY/pixelSize - 7, 
                '#000000', 
                pixelSize
            );
            
            // 嘴巴（居中）
            if(characterParts.head.mouth_type === 'smile') {
                drawPixel(ctx, 
                    headStartX/pixelSize + headWidth/2 - 1, 
                    startY/pixelSize - 4, 
                    '#000000', 
                    pixelSize
                );
                drawPixel(ctx, 
                    headStartX/pixelSize + headWidth/2, 
                    startY/pixelSize - 4, 
                    '#000000', 
                    pixelSize
                );
            }
            
            // 头发
            for(let x = -1; x < headWidth + 1; x++) {
                drawPixel(ctx, 
                    headStartX/pixelSize + x, 
                    startY/pixelSize - 11, 
                    characterParts.head.hair_color, 
                    pixelSize
                );
            }
        }
    }

    // 为每个生成按钮添加事件监听器
    document.querySelectorAll('.generate-btn').forEach(button => {
        button.addEventListener('click', function() {
            const type = this.dataset.type;
            const canvas = document.getElementById(`${type}-canvas`);
            
            fetch(`/generate/${type}`)
                .then(response => response.json())
                .then(data => {
                    characterParts[type] = data;
                    
                    switch(type) {
                        case 'head':
                            drawHead(canvas, data);
                            break;
                        case 'body':
                            drawBody(canvas, data);
                            break;
                        case 'clothes':
                            drawClothes(canvas, data);
                            break;
                        case 'weapon':
                            drawWeapon(canvas, data);
                            break;
                    }
                    
                    updatePreview();
                });
        });
    });

    // 在文件末尾添加随机生成全部功能
    document.getElementById('random-all-btn').addEventListener('click', function() {
        const parts = ['head', 'body', 'clothes', 'weapon'];
        parts.forEach(type => {
            const button = document.querySelector(`.generate-btn[data-type="${type}"]`);
            button.click();
        });
    });

    // 添加保存功能
    document.getElementById('save-btn').addEventListener('click', function() {
        const previewCanvas = document.getElementById('preview-canvas');
        // 创建一个链接来下载图片
        const link = document.createElement('a');
        link.download = 'my-pixel-character.png';
        link.href = previewCanvas.toDataURL();
        link.click();
    });

    // 添加下拉框选择事件处理
    document.querySelectorAll('select').forEach(select => {
        select.addEventListener('change', function() {
            const type = this.id.split('-')[0]; // 获取类型（head/body/clothes/weapon）
            const feature = this.id.split('-')[1]; // 获取特征（hair-style/eye-type等）
            const value = this.value;
            
            if (value && characterParts[type]) {
                characterParts[type][feature] = value;
                const canvas = document.getElementById(`${type}-canvas`);
                
                switch(type) {
                    case 'head':
                        drawHead(canvas, characterParts[type]);
                        break;
                    case 'body':
                        drawBody(canvas, characterParts[type]);
                        break;
                    case 'clothes':
                        drawClothes(canvas, characterParts[type]);
                        break;
                    case 'weapon':
                        drawWeapon(canvas, characterParts[type]);
                        break;
                }
                
                updatePreview();
            }
        });
    });
}); 